package fun.cyhgraph.controller.user;

import fun.cyhgraph.common.ErrorCode;
import fun.cyhgraph.exception.BusinessException;
import fun.cyhgraph.exception.ThrowUtils;
import fun.cyhgraph.model.dto.CartDTO;
import fun.cyhgraph.model.entity.Cart;
import fun.cyhgraph.model.entity.User;
import fun.cyhgraph.result.Result;
import fun.cyhgraph.service.CartService;
import fun.cyhgraph.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user/cart")
@Tag(name = "购物车")
@Slf4j
public class CartController {

    @Resource
    private CartService cartService;
    @Resource
    private UserService userService;

    @PostMapping("/add")
    @Operation(summary = "将菜品/套餐添加进购物车")
    public Result add(@RequestBody CartDTO cartDTO , HttpServletRequest request){
        User loginUser = userService.getLoginUser(request);
        if (loginUser == null){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR , "请先登录");
        }
        log.info("将如下菜品/套餐添加进购物车：{}", cartDTO);
        cartService.add(cartDTO);
        return Result.success();
    }

    @PutMapping("/sub")
    @Operation(summary = "更改菜品/套餐数量")
    public Result sub(@RequestBody CartDTO cartDTO){
        log.info("将如下菜品/套餐数量减一：{}", cartDTO);
        cartService.sub(cartDTO);
        return Result.success();
    }

    @Operation(summary = "展示用户的购物车列表")
    @GetMapping("/list")
    public Result<List<Cart>> getList(){
        log.info("拿到当前用户的购物车列表");
        List<Cart> cartList = cartService.getList();
        return Result.success(cartList);
    }

    @DeleteMapping("/clean")
    @Operation(summary = "清空购物车")
    public Result cleanCart(){
        log.info("清空购物车");
        cartService.clean();
        return Result.success();
    }
}
